<!--
 * @Author: lwHao
 * @Date: 2020-09-17 16:57:55
 * @LastEditors: lwHao
 * @LastEditTime: 2020-09-20 15:03:34
-->
<!--
 * @Author: lwHao
 * @Date: 2020-09-17 16:57:55
 * @LastEditors: lwHao
 * @LastEditTime: 2020-09-17 17:04:11
-->
<template>
  <div class="home-page">
    <div class="banner">
      <div class="container">
        <h1 class="logo-font">conduit</h1>
        <p>A place to share your knowledge.</p>
      </div>
    </div>

    <div class="container page">
      <div class="row">
        <div class="col-md-9">
          <div class="feed-toggle">
            <ul class="nav nav-pills outline-active">
              <li class="nav-item" v-if="user">
                <nuxt-link :to="{
                  name: 'home',
                  query: {
                    tab: 'your_feed'
                  }
                }" class="nav-link" exact :class="{active: tab === 'your_feed'}">Your Feed</nuxt-link>
              </li>
              <li class="nav-item">
                <nuxt-link :to="{
                  name: 'home',
                }" class="nav-link" exact :class="{active: tab === 'global_feed'}">Global Feed</nuxt-link>
              </li>
              <li v-if="tag" class="nav-item">
                <nuxt-link :to="{
                  name: 'home',
                  tag: tag,
                  tab: 'tag'
                }" class="nav-link" exact :class="{active: tab === 'tag'}"># {{ tag }}</nuxt-link>
              </li>
            </ul>
          </div>

          <div class="article-preview" v-for="article in articles" :key="article.slug">
            <div class="article-meta">
              <nuxt-link :to="{
                name: 'profile',
                params: {
                  username: article.author.username
                }
              }">
                <img :src="article.author.image" />
              </nuxt-link>
              <div class="info">
                <nuxt-link :to="{
                  name: 'profile',
                  params: {
                    username: article.author.username
                  }
                }" class="author">{{ article.author.username }}</nuxt-link>
                <span class="date">{{ article.updatedAt | date('MMM DD,YYYY') }}</span>
              </div>
              <button class="btn btn-outline-primary btn-sm pull-xs-right" :class="{active: article.favorited}" :disabled="article.disabled" @click="onFavorite(article)">
                <i class="ion-heart"></i>
                {{ article.favoritesCount }}
              </button>
            </div>
            <nuxt-link :to="{
              name: 'article',
              params: {
                slug: article.slug
              }
            }" href class="preview-link">
              <h1>{{ article.title }}</h1>
              <p>{{ article.description}}</p>
              <span>Read more...</span>
            </nuxt-link>
          </div>
          <div v-if="!articlesCount">No articles are here... yet.</div>
          <!-- 分页列表 -->
          <nav>
            <ul class="pagination">
              <li class="page-item" v-for="item in totalPage" :class="{active:item === page}">
                <nuxt-link :to="{
                  name: 'home',
                  query: {
                    page: item,
                    tag: $route.query.tag,
                    tab: tab
                  }
                }" class="page-link">{{item}}</nuxt-link>
              </li>
            </ul>
          </nav>
          <!-- 分页列表 -->
        </div>

        <div class="col-md-3">
          <div class="sidebar">
            <p>Popular Tags</p>

            <div class="tag-list">
              <nuxt-link v-for="(tag, index) in tags" :key="index" :to="{ name:'home', query: {page, tag, tab: 'tag'}}" class="tag-pill tag-default">{{ tag }}</nuxt-link>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getArticles, getTags, getFeedArticle, deleteFavorite, addFavorite } from '@/api/article'
import { mapState } from 'vuex'
export default {
  name: 'HomeIndex',
  // watchQuery: ['page'],
  watchQuery: true,
  async asyncData({ isDev, route, store, env, params, query, req, res, redirect, error }) {
    const page = Number.parseInt(query.page || 1)
    const limit = 20
    const tab = query.tab || 'global_feed'
    const tag = query.tag
    const loadArticle = tab === 'your_feed' ? getFeedArticle : getArticles
    const [articleRes, tagRes] = await Promise.all([
      loadArticle({
        limit,
        offset: (page - 1) * limit,
        tag: tag
      }),
      getTags()])
    const { articles, articlesCount } = articleRes.data
    const tags = tagRes.data.tags.map(tag => tag.replace(/\u200c/g, '')).filter(tag => !!tag)
    if (articlesCount > 0) {
      articles.forEach(item => {
        item.disabled = false
      })
    }
    // console.log(tags);

    return {
      articles,
      articlesCount,
      limit,
      page,
      tags,
      tab,// 选项卡
      tag // 数据标签
    }
  },
  computed: {
    ...mapState(['user']),
    totalPage() {
      return Math.ceil(this.articlesCount / this.limit)
    }
  },
  methods: {
    async onFavorite(article) {
      article.disabled = true
      try {
        const favAction = article.favorited ? deleteFavorite: addFavorite
        const response = await favAction(article.slug)
        const { favorited, favoritesCount } = response.data.article
        article.favorited = favorited
        article.favoritesCount = favoritesCount
      } finally {
        article.disabled = false
      }

    }
  }
}
</script>

<style>
</style>